import { promises } from "dns";
import { ipcMain, dialog, BrowserWindow, app } from "electron";
import fs from "fs";
import path, { resolve } from "path";
// import device from "diskinfo";
export default {
	bind() {
		ipcMain.handle("test1", (event, arg) => {
			console.log(arg);
		});
		ipcMain.handle("readDir", async (event, arg) => {
			const d = require("diskinfo"); // 需安装diskinfo依赖
			// let deviceList = await d.getDrives();
			// console.log("#debug#🚀 ~ ipcMain.handle ~ deviceList:", deviceList);
			let deviceList = [];

			d.getDrives(function (err: any, aDrives: any) {
				for (var i = 0; i < aDrives.length; i++) {
					deviceList.push(aDrives[i]);
					console.log("磁盘：" + aDrives[i].mounted);
					console.log("磁盘总内存：" + aDrives[i].blocks);
					console.log("磁盘已用内存：" + aDrives[i].used);
					console.log("磁盘可用内存：" + aDrives[i].available);
					console.log("磁盘已用内存百分比： " + aDrives[i].capacity);
					console.log("-----------------------------------------");
				}
			});
			console.log("#debug#🚀 ~ ipcMain.handle ~ deviceList:", deviceList);
			// console.log("#debug#🚀 ~ ipcMain.on ~ arg:", arg);
			let dir = "./";
			let fileDir = path.resolve(__dirname, arg ? arg : "./");
			let files = fs.readdirSync(fileDir, { encoding: "utf8" });
			return new Promise((resolve, reject) => {
				//异步读取目录内容;
				/*
				 * 异步读取目录内容，（若不存在目录，则发生异常）
				 * @param path {string | Buffer | URL |} 目录名
				 * @param options {Object | string}
				 *          encoding {string | null}, 编码方式，默认值是 'utf8'
				 *          withFileTypes {boolean}, 返回的文件对象是否包含文件类型，默认值为 false
				 * @param callback {Function} 回调函数
				 *          err {Error} 读取目录内容时抛出的错误
				 *          files {string[] | Buffer[] | fs.Dirent[]} 读取到的目录内容
				 */
				fs.readdir(fileDir, { encoding: "utf8", withFileTypes: false }, (err, files) => {
					if (err) throw err;
					// console.log("读取的目录内容：", files);
					let filesArr = [];

					for (let item of files) {
						let file = {
							name: item,
							type: ""
						};
						const fileOrDirPath = `${fileDir}/${item}`;

						// console.log("#debug#🚀 ~ returnnewPromise ~ fileOrDirPath:", fileOrDirPath);
						let type = fs.statSync(fileOrDirPath);
						if (type.isFile()) {
							file.type = "file";
							// console.log(`这是一个文件： ${fileOrDirPath}`);
						} else if (type.isDirectory()) {
							file.type = "dir";
							// console.log(`这是一个目录： ${fileOrDirPath}`);
						}
						filesArr.push(file);
					}
					resolve(filesArr);
				});
			});
		});
		ipcMain.handle("readDirSync", (event, arg) => {
			console.log("#debug#🚀 ~ ipcMain.on ~ arg:", arg);
			let dir = "./";
			let fileDir = path.resolve(__dirname, dir);
			let files = fs.readdirSync(fileDir, { encoding: "utf8" });
			return files;
			// 异步读取目录内容
			//   fs.readdir(fileDir, { encoding: "utf8" }, (err, files) => {
			//     if (err) throw err;
			//     console.log("读取的目录内容：", files);
			//     return files;
			//   });
		});
	}
};
